<?php
declare(strict_types=1);
/**
 * Created by PhpStorm
 * User: Administrator
 * Date: 2022/10/21
 * Time: 17:20:09
 */

namespace app\common\service\DecorateService;

use app\model\BbcModel\Decorate;
use app\model\BbcModel\DecorateTab;
use app\Normal;

class DecorateTabService extends \app\BaseService
{
    public function lists( array $param): array{
        $page = (isset($param['page']) && $param['page'] != '') ? $param['page'] : 1;
        $limit = (isset($param['limit']) && $param['limit'] != '') ? $param['limit'] : 20;
        $where = [
          ['cid','=',$param['cid']],
          ['df','=',0],
        ];
        $status = $param['status'] ?? 0;
        if($status == 1){ //1-未发布，2-已发布
            $where[] = ['release_status','=',0];
        }else if($status == 2){
            $where[] = ['release_status','=',1];
        }
        $data_lists = DecorateTab::instance()->where($where)->page((int)$page)->limit((int)$limit)->field('id,name,cd')->select()->toArray();
        $b_decorate = Decorate::instance()->where(['type'=>2,'cid'=>$param['cid']])->value('tab_id');
        /*if($b_decorate){
            $b_decorate_arr = explode(',',$b_decorate);
        }else{
            $b_decorate_arr = [];
        }*/
        $c_decorate = Decorate::instance()->where(['type'=>1,'cid'=>$param['cid']])->value('tab_id');
        /*if($c_decorate){
            $c_decorate_arr = explode(',',$c_decorate);
        }else{
            $c_decorate_arr = [];
        }*/
        foreach ($data_lists as $k=>$v){
            $data_lists[$k]['is_b_home'] = 0;
            $data_lists[$k]['is_c_home'] = 0;
            if($v['id'] == $b_decorate){
                $data_lists[$k]['is_b_home'] = 1;
            }
            if($v['id'] == $c_decorate){
                $data_lists[$k]['is_c_home'] = 1;
            }
            $data_lists[$k]['cd'] = date('Y-m-d H:i:s',$v['cd']);
        }
        $total = DecorateTab::instance()->where($where)->count();
        return Normal::returnCode(Normal::SUC,'获取成功',['list'=>$data_lists,'total'=>$total]);
    }

    public function add(array $param): array {
        if(!isset($param['name']) || !$param['name']){
            return Normal::returnCode(Normal::FAIL,'页面名称不能为空');
        }
        $param['name'] = trim($param['name']);
        if(!isset($param['content']) || !$param['content']){
            return Normal::returnCode(Normal::FAIL,'组件不能为空');
        }
        if(DecorateTab::instance()->info(['cid'=>$param['cid'],'name'=>$param['name'],'df'=>0])){
            return Normal::returnCode(Normal::FAIL,'名称已存在');
        }
        $insertData['name'] = $param['name'];
        $insertData['cid'] = $param['cid'];
        $insertData['cb_id'] = $param['cb_id'];
        $insertData['md'] = time();
        $insertData['cd'] = time();
        $insertData['content'] = json_encode($param['content']);
        $insertData['release_content'] = json_encode($param['content']);
        $insertData['release_status'] = 0;
        $res = DecorateTab::instance()->insert($insertData);
        if($res == false){
            return Normal::returnCode(Normal::FAIL,'新增失败');
        }
        return Normal::returnCode(Normal::SUC,'新增成功');
    }

    public function details( array $param): array{
        $is_preview = $param['is_preview'] ?? 0; //0-详情，1-预览
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'缺少页面ID');
        }
        $details = DecorateTab::instance()->info(['id'=>$param['id'],'cid'=>$param['cid'],'_fields_'=>'id,name,content,release_content,release_status']);
        if(!$details){
            return Normal::returnCode(Normal::FAIL,'数据不存在');
        }
        if($is_preview == 1){ //预览
            $details['content'] = json_decode($details['content'],true);
        }else{
            $details['content'] = json_decode($details['release_content'],true);
        }
        return Normal::returnCode(Normal::SUC,'请求成功',$details);
    }

    public function del( array $param): array{
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'缺少微页面ID');
        }
        $info = DecorateTab::instance()->where(['id'=>$param['id'],'df'=>0,'cid'=>$param['cid']])->find();
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'数据不存在');
        }
        $checkData = $this->checkData($param);
        if(in_array($param['id'],$checkData['page'])){
            return Normal::returnCode(Normal::FAIL,'微页面被使用无法删除');
        }
        $res = DecorateTab::instance()->where(['id'=>$param['id']])->update(['df'=>1,'md'=>time()]);
        if($res == false){
            return Normal::returnCode(Normal::FAIL,'删除失败');
        }
        return Normal::returnCode(Normal::SUC,'删除成功');
    }

    public function edit( array $param): array{
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'缺少微页面ID');
        }
        $info = DecorateTab::instance()->info(['id'=>$param['id'],'cid'=>$param['cid']]);
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'微页面不存在');
        }
        if(!isset($param['name']) || !$param['name']){
            return Normal::returnCode(Normal::FAIL,'微页面名称不能为空');
        }
        if(!isset($param['content']) || !$param['content']){
            return Normal::returnCode(Normal::FAIL,'组件不能为空');
        }
        if(DecorateTab::instance()->where(['cid'=>$param['cid'],'name'=>$param['name'],'df'=>0])->where('id','<>',$param['id'])->find()){
            return Normal::returnCode(Normal::FAIL,'名称已存在');
        }
        $param['content'] = json_encode($param['content']);
        if($param['content'] != $info['content']){ //修改过组件内容;
            $res = DecorateTab::instance()->where(['id'=>$param['id']])->update(['name'=>$param['name'],'md'=>time(),'release_content'=>$param['content'],'release_status'=>0]);
        }else{
            $res = DecorateTab::instance()->where(['id'=>$param['id']])->update(['name'=>$param['name'],'md'=>time()]);
        }
        if($res == false){
            return Normal::returnCode(Normal::FAIL,'编辑失败');
        }
        return Normal::returnCode(Normal::SUC,'编辑成功');
    }

    public function release( array $param): array{
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'缺少微页面ID');
        }
        $info = DecorateTab::instance()->where(['id'=>$param['id'],'cid'=>$param['cid'],'df'=>0])->find();
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'数据不存在');
        }
        $res = DecorateTab::instance()->where(['id'=>$param['id']])->update(['release_status'=>1,'md'=>time(),'content'=>$info['release_content']]);
        if($res == false){
            return Normal::returnCode(Normal::FAIL,'发布失败');
        }
        return Normal::returnCode(Normal::SUC,'发布成功');
    }

    /**
     * 获取使用的长图、微页面、商品组ID
     * @return void
     */
    public function checkData( array $param): array{
        $long_img = [];
        $goods_group = [];
        $page = Decorate::instance()->where(['cid'=>$param['cid'],'df'=>0])->column('tab_id','tab_id');

        DecorateTab::instance()->where(['cid'=>$param['cid'],'df'=>0])->chunk(100,function ($datum) use(&$long_img,&$goods_group,&$page){
            $datum_arr = $datum->toArray();
            foreach ($datum_arr as $data) {
                $content_arr = json_decode($data['content'], true);
                $release_content_arr = json_decode($data['release_content'], true);
                if ($content_arr) {
                    //图文广告-new_image_ad,魔方-cube_v3,图文导航-image_text_nav
                    foreach ($content_arr as $key => $val) {
                        if (in_array($val['type'], ['new_image_ad', 'cube_v3', 'image_text_nav']) && isset($val['data']['sub_entry'])) {
                            $body = $val['data']['sub_entry'];
                            foreach ($body as $k => $v) {
                                if (isset($v['link_type'])) { //设置了跳转链接
                                    if ($v['link_type'] == 1 && $v['link_id']) { //商品组
                                        $goods_group[$v['link_id']] = $v['link_id'];
                                    }
                                    if ($v['link_type'] == 2 && $v['link_id']) { //微页面
                                        $page[$v['link_id']] = $v['link_id'];
                                    }
                                    if ($v['link_type'] == 3 && $v['link_id']) { //长图
                                        $long_img[$v['link_id']] = $v['link_id'];
                                    }
                                }
                            }
                        }
                    }
                }

                if ($release_content_arr) {
                    //图文广告-new_image_ad,魔方-cube_v3,图文导航-image_text_nav
                    foreach ($release_content_arr as $key => $val) {
                        if (in_array($val['type'], ['new_image_ad', 'cube_v3', 'image_text_nav']) && isset($val['data']['sub_entry'])) {
                            $body = $val['data']['sub_entry'];
                            foreach ($body as $k => $v) {
                                if (isset($v['link_type'])) { //设置了跳转链接
                                    if ($v['link_type'] == 1 && $v['link_id']) { //商品组
                                        $goods_group[$v['link_id']] = $v['link_id'];
                                    }
                                    if ($v['link_type'] == 2 && $v['link_id']) { //微页面
                                        $page[$v['link_id']] = $v['link_id'];
                                    }
                                    if ($v['link_type'] == 3 && $v['link_id']) { //长图
                                        $long_img[$v['link_id']] = $v['link_id'];
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
        $page = array_values($page);
        $long_img = array_values($long_img);
        $goods_group = array_values($goods_group);
        return ['page'=>$page,'long_img'=>$long_img,'goods_group'=>$goods_group];
    }
}